﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace MapleLeaf.Pay {

    public static class ObjectBuilder {

        public static object New(Type type) {
            if (!NewExpressions.TryGetValue(type, out Func<object> func)) {
                func = Expression.Lambda<Func<object>>(Expression.New(type), new ParameterExpression[0]).Compile();
                NewExpressions[type] = func;
            }
            return func();
        }


        static ObjectBuilder() {

            NewExpressions = new Dictionary<Type, Func<object>>();
        }

        internal static readonly Dictionary<Type, Func<object>> NewExpressions;
    }
    public static class ObjectBuilder<T> {

        public static T New() {
            return (T)ObjectBuilder.New(typeof(T));
        }
        static ObjectBuilder() {

            Propertys = typeof(T).GetProperties().ToDictionary((PropertyInfo p) => p.Name, (PropertyInfo p) => p);
        }
        public static readonly Dictionary<string, PropertyInfo> Propertys;
    }
}
